<?php

namespace App\Http\Controllers\v3;

use App\Http\Controllers\Controller;
use App\Models\Users;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Cache\Simple\RedisCache;


/**
 * 登录相关
 * Class CateController
 * @package App\Http\Controllers
 */
class AuthController extends Controller {

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login(){
//        try {
            $code = request('code','');
            $app = app('wechat.mini_program');
            $predis = app('redis')->connection()->client();
            $cache = new RedisCache($predis);
            $app->rebind('cache', $cache);
            $data = $app->auth->session($code);
            $user = Users::where('openid',$data['openid'])->first();
            if(!$user){
                //不存在创建新用户
                $user = Users::create([
                    'openid' => $data['openid'],
                    'password' => bcrypt($data['openid']),
                    'register_at' => Carbon::now(),
                    'login_at' => Carbon::now(),
                ]);
            }
            return $this->returnJson(0,'',['user'=>['id'=>$user['id'],'openid'=>$data['openid']]]);
//        } catch (\Exception $e) {
//            return $this->returnJson(1, '登录失败');
//        }
    }

}
